const db = require('db/blackList.js');
const common = require('lib/utils/common.js');
const xlsx = require('node-xlsx');

/** @name 黑名单列表 **/
exports.list = async ctx => {
	const { number, realname, phone } = ctx.query;
	const options = {
		...common.YD_getPageDefault(ctx),
		number, realname, phone
	}
	const totalRes = await db.yd_count(options);
  const total = totalRes[0].count || 0;
  const rows = await db.yd_list(options);
	ctx.success({
    total,
    rows
  });
};

/** @name 导出黑名单信息 **/
exports.export = async ctx => {
	// excel相关
	const header = ['车牌号码', '用户名称', '联系电话', '备注'];
	const keys = ['number', 'realname', 'phone', 'note'];

	// 拉取数据库数据
	const rows = await db.yd_export();

	// 数据处理
	const body = [];
	let bodyItem = [];
	rows.forEach(item => {
		keys.forEach(key => {
			bodyItem.push(item[key]);
		})
		body.push(bodyItem);
		bodyItem = [];
	})

	// 完整excel数据
	const data = [header, ...body];
	console.log('data', data)
	const buffer = xlsx.build([{name: 'sheet1', data: data}]);
	const filename = encodeURI(`${common.YD_dateFormat('empty')}-车辆黑名单信息.xlsx`);
	//设置响应头
	ctx.set('Content-Type', 'application/vnd.openxmlformats');
	ctx.set('Content-Disposition', 'attachment; filename=' + filename);
	//返回结果
	ctx.body = buffer;
};

/** @name 编辑黑名单 **/
exports.edit = async ctx => {
	if(ctx.requiredParams(['id', 'note'])) return;
	const { id, note } = ctx.request.body;
	const currentTime = common.YD_dateFormat()
	const options = {
		note,
		updateTime: currentTime,
	}
	await db.yd_update(options, { id });
	ctx.success('黑名单编辑成功');
};

/** @name 删除黑名单 **/
exports.delete = async ctx => {
	if(ctx.requiredParams(['id'])) return;
	const { id } = ctx.request.body;
	await db.yd_delete(id);
	ctx.success('黑名单删除成功');
};
